package sush.global.cammail.provider;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;

public class DatabaseProvider extends ContentProvider {
	
	private DatabaseHelper _dbHelper;
	private static UriMatcher _uriMatcher;
	
	private static final int TASKS = 1;
	private static final int TEMPLATES = 2;
	private static final int FIELDS = 3;
	private static final int DROPDOWNVALUES = 4;
	private static final int TASKIMAGES = 5;
	
	static {
		_uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
		
		_uriMatcher.addURI(Scheme.AUTHORITY, Scheme.getTaskTable().getTableName(), TASKS);
		_uriMatcher.addURI(Scheme.AUTHORITY, Scheme.getTemplateTable().getTableName(), TEMPLATES);
		_uriMatcher.addURI(Scheme.AUTHORITY, Scheme.getFieldTable().getTableName(), FIELDS);
		_uriMatcher.addURI(Scheme.AUTHORITY, Scheme.getDropDownValueTable().getTableName(), DROPDOWNVALUES);
		_uriMatcher.addURI(Scheme.AUTHORITY, Scheme.getTaskImageTable().getTableName(), TASKIMAGES);
	}
	
	@Override
	public boolean onCreate() {
		_dbHelper = new DatabaseHelper(getContext());
		return true;
	}
	
	@Override
	public String getType(Uri uri) {
		BaseTable table = getTable(uri);
		return table.getContentType();
	}
	
	@Override
	public int delete(Uri uri, String whereClause, String[] whereArgs) {
		SQLiteDatabase db = _dbHelper.getWritableDatabase();
		BaseTable table = getTable(uri);
		int count = db.delete(table.getTableName(), whereClause, whereArgs);
		getContext().getContentResolver().notifyChange(uri, null);
		return count;
	}

	@Override
	public Uri insert(Uri uri, ContentValues initValues) {
		BaseTable table = getTable(uri);
		ContentValues values = initValues != null ?
				initValues : new ContentValues();
		
		SQLiteDatabase db = _dbHelper.getWritableDatabase();
		long rowId = db.insert(table.getTableName(), null, values);
		if (rowId > 0) {
			Uri newUri = ContentUris.withAppendedId(table.getContentUri(), rowId);
			getContext().getContentResolver().notifyChange(newUri, null);
			return newUri;
		}
		throw new SQLException("Failed to insert row into " + uri);
	}

	@Override
	public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
		SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
		BaseTable table = getTable(uri);
		qb.setTables(table.getTableName());
		SQLiteDatabase db = _dbHelper.getReadableDatabase();
		Cursor c = qb.query(db, projection, selection, selectionArgs, null, null, sortOrder);
		c.setNotificationUri(getContext().getContentResolver(), uri);
		return c;
	}

	@Override
	public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
		SQLiteDatabase db = _dbHelper.getWritableDatabase();
		BaseTable table = getTable(uri);
		int count = db.update(table.getTableName(), values, selection, selectionArgs);
		return count;
	}
	
	private BaseTable getTable(Uri uri) {
		BaseTable table;
		switch(_uriMatcher.match(uri)) {
			case TASKS:
				table = Scheme.getTaskTable();
				break;
			case TEMPLATES:
				table = Scheme.getTemplateTable();
				break;
			case FIELDS:
				table = Scheme.getFieldTable();
				break;
			case DROPDOWNVALUES:
				table = Scheme.getDropDownValueTable();
				break;
			case TASKIMAGES:
				table = Scheme.getTaskImageTable();
				break;
			default:
				throw new IllegalArgumentException("getTable() - unknown URI: " + uri);
		}
		return table;
	}
	
	private static class DatabaseHelper extends SQLiteOpenHelper {

		public DatabaseHelper(Context context) {
			super(context, Scheme.DATABASE_NAME, null, Scheme.DATABASE_VERSION);
		}

		@Override
		public void onCreate(SQLiteDatabase db) {
			TaskTable taskTable = Scheme.getTaskTable();
			db.execSQL("CREATE TABLE " + taskTable.getTableName() + " ("
	                   + taskTable._ID + " INTEGER PRIMARY KEY,"
	                   + taskTable.COLUMN_NAME_DATECREATED + " " + taskTable.COLUMN_TYPE_DATECREATED + ","
	                   + taskTable.COLUMN_NAME_TITLE + " " + taskTable.COLUMN_TYPE_TITLE + ","
	                   + taskTable.COLUMN_NAME_EMAILSTATUS + " " + taskTable.COLUMN_TYPE_EMAILSTATUS + ","
	                   + taskTable.COLUMN_NAME_EMAIL1 + " " + taskTable.COLUMN_TYPE_EMAIL1 + ","
	                   + taskTable.COLUMN_NAME_EMAIL2 + " " + taskTable.COLUMN_TYPE_EMAIL2
	                   + ");");
			
			TemplateTable templateTable = Scheme.getTemplateTable();
			db.execSQL("CREATE TABLE " + templateTable.getTableName() + " ("
	                   + templateTable._ID + " INTEGER PRIMARY KEY,"
	                   + templateTable.COLUMN_NAME_NAME + " " + templateTable.COLUMN_TYPE_NAME
	                   + ");");
			
			FieldTable fieldTable = Scheme.getFieldTable();
			db.execSQL("CREATE TABLE " + fieldTable.getTableName() + " ("
	                   + fieldTable._ID + " INTEGER PRIMARY KEY,"
	                   + fieldTable.COLUMN_NAME_IDTEMPLATE + " " + fieldTable.COLUMN_TYPE_IDTEMPLATE + ","
	                   + fieldTable.COLUMN_NAME_IDTASK + " " + fieldTable.COLUMN_TYPE_IDTASK + ","
	                   + fieldTable.COLUMN_NAME_LABEL + " " + fieldTable.COLUMN_TYPE_LABEL + ","
	                   + fieldTable.COLUMN_NAME_POS + " " + fieldTable.COLUMN_TYPE_POS + ","
	                   + fieldTable.COLUMN_NAME_TYPE + " " + fieldTable.COLUMN_TYPE_TYPE + ","
	                   + fieldTable.COLUMN_NAME_VALUE + " " + fieldTable.COLUMN_TYPE_VALUE + ","
	                   + fieldTable.COLUMN_NAME_ISMULTI + " " + fieldTable.COLUMN_TYPE_ISMULTI
	                   + ");");
			
			DropDownValueTable dropDownValue = Scheme.getDropDownValueTable();
			db.execSQL("CREATE TABLE " + dropDownValue.getTableName() + " ("
	                   + dropDownValue._ID + " INTEGER PRIMARY KEY,"
	                   + dropDownValue.COLUMN_NAME_IDFIELD + " " + dropDownValue.COLUMN_TYPE_IDFIELD + ","
	                   + dropDownValue.COLUMN_NAME_VALUE + " " + dropDownValue.COLUMN_TYPE_VALUE
	                   + ");");
			
			TaskImageTable taskImageTable = Scheme.getTaskImageTable();
			db.execSQL("CREATE TABLE " + taskImageTable.getTableName() + " ("
	                   + taskImageTable._ID + " INTEGER PRIMARY KEY,"
	                   + taskImageTable.COLUMN_NAME_IDTASK + " " + taskImageTable.COLUMN_TYPE_IDTASK + ","
	                   + taskImageTable.COLUMN_NAME_PATH + " " + taskImageTable.COLUMN_TYPE_PATH
	                   + ");");
		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {			
		}
		
	}
}
